/*
 * Copyright 2003-2007 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

package com.colony.remote.rpc;

import com.argot.DynamicTypeMap;
import com.argot.TypeException;
import com.argot.TypeLibrary;
import com.argot.TypeMapCore;
import com.argot.network.TypeServer;
import com.argot.remote.MetaObject;

import com.colony.ColonyEnvironment;
import com.colony.IColonyServer;

import com.colony.remote.RemoteException;
import com.colony.transport.Server;

public class RpcServer
implements IColonyServer
{
	private boolean _isBound;
	private MetaObject _baseObject;
	private Server _transport;
	
	private ColonyEnvironment _environment;
	private TypeLibrary _library;
	private RpcDelegateFactory _delegateFactory;
	private DynamicTypeMap _dynamicTypeMap;
	private TypeServer _typeServer;
	
	public RpcServer( Server transport, MetaObject baseObject )
	{
		_isBound = false;
		_transport = transport;
		_baseObject = baseObject;
	}
	
	public RpcServer( Server transport )
	{
		this( transport, null);
	}
	
	public ColonyEnvironment getEnvironment()
	{
		return _environment;
	}

	public void bind( ColonyEnvironment environment ) 
	throws RemoteException, TypeException
	{
		if ( _isBound ) throw new RemoteException( "Client already bound" );
		_isBound = true;
		
		_environment = environment;
		_library = environment.getTypeLibrary();
		
		_dynamicTypeMap = new DynamicTypeMap( _library );
		TypeMapCore.mapMeta( _dynamicTypeMap , _library );
		_dynamicTypeMap.map( 22, _library.getId("dictionary.map"));
		_dynamicTypeMap.map( 23, _library.getId("dictionary.words"));
		_dynamicTypeMap.map( 24, _library.getId("dictionary.definition"));
		_dynamicTypeMap.map( 25, _library.getId("dictionary.entry"));	
		_dynamicTypeMap.map( 26, _library.getId("meta.envelop"));
		_dynamicTypeMap.map( 27, _library.getId("meta.definition#envelop"));		
		
		_delegateFactory = new RpcDelegateFactory();
		RpcMetaServer rpcHost = new RpcMetaServer( _delegateFactory, _environment.getHostContainer(), _dynamicTypeMap);
		_typeServer = new TypeServer( _library, _dynamicTypeMap, rpcHost );	
		_transport.setTypeLink(_typeServer);
		if (_baseObject != null)
		{
			_typeServer.setBaseObject( _baseObject );
		}
	}

	public boolean isBound()
	{
		return _isBound;
	}
	
	public void setBaseObject( MetaObject baseObject )
	{	
		if ( isBound() )
		{
			_typeServer.setBaseObject( _baseObject );
		}
	}

}
